import { Listr } from "listr2";
import { rollup, OutputOptions } from "rollup";
import {
  App_Env_Enum,
  App_Modules_Enum,
  App_NODE_ENV_Enum,
  Argv_Enum,
} from "../enum/app.enum";
import { FileService } from "../src/main/service/base/fs";
import { Env, getArgv } from "../utils/env";
import rollupConfig from "../config/rollup.config";
import { AppConfig } from "../config/app.config";
import buildConfig from '../config/build.json'
import { name ,author } from '../package.json'
import fs from 'fs'
import { resolve } from "path";

Env.setEnv(App_Env_Enum.NODE_ENV, App_NODE_ENV_Enum.PRODUCTION);

//编译
async function compile(): Promise<void> {
  //清空dist文件夹
  FileService.deleteDirectory(resolve("dist"));

  console.log("开始编译..");
  const tasksLister = new Listr(
    [
      {
        title: "编译主进程..",
        task: async () => {
          try {
            const config = rollupConfig(App_Modules_Enum.MAIN);
            const build = await rollup(config);
            await build.write(config.output as OutputOptions);
          } catch (error) {
            console.error(`编译主进程出错`);
            return Promise.reject(error);
          }
        },
      },
      {
        title: "编译预加载脚本..",
        task: async () => {
          try {
            const config = rollupConfig(App_Modules_Enum.PRELOAD);
            const build = await rollup(config);
            await build.write(config.output as OutputOptions);
          } catch (error) {
            console.error(`编译预加载脚本出错`);
            return Promise.reject(error);
          }
        },
      },
      {
        title: "编译渲染进程..",
        task: async (_, tasks) => {
          try {
            const { build } = await import("vite");
            await build({ configFile: resolve("config/vite.config.mts") });
            tasks.output = `编译任务完成`;
          } catch (error) {
            console.error(`编译渲染进程出错`);
            return Promise.reject(error);
          }
        },
      },
    ],
    {
      //任务可以并行执行（如果可能）
      concurrent: true,
      //遇到错误时立即停止所有任务并退出程序
      exitOnError: true,
    }
  );
  await tasksLister.run();
}

//打包
async function build(target?: string): Promise<void> {

  console.log("配置打包项");

  const buildTarget = {
    target: "nsis",
    arch: [
      "x64"
    ]
  }

  buildConfig.asar = true
  //需要安装python 可能是有原生Node模块的原因
  // buildCfg.afterPack = "scripts/buildAfterPack.js"

  if(!target)buildTarget.arch = ['x64', 'ia32']
  else if(target === 'win32')buildTarget.arch = ['ia32']
  else if(target === 'win64')buildTarget.arch = ['x64']

  buildConfig.win.target = [buildTarget]

  buildConfig.productName = name
  buildConfig.appId = `org.${name}.${author.name}`
  
  buildConfig.publish = [
    {
      provider: AppConfig.BUILD_PROVIDER,
      url: AppConfig.SERVICE_URL + AppConfig.UPDATE_BASE_API
    }
  ]
  
  //写入配置
  fs.writeFileSync('config/build.json', JSON.stringify(buildConfig, null, 2)); 

  //清空build文件夹
  FileService.deleteDirectory(resolve("build"));

  console.log('开始打包')
}

//启动
async function start(): Promise<void> {
  try {
    //获取要打包的系统架构
    const target = getArgv(Argv_Enum.TARGET);
    await compile();
    await build(target);
  } catch(err) {
    console.error('构建出错：' + err)
    process.exit(1);
  }
}

start();
